<template>
  <div class="center">
  <bubbleMenu />
  <!-- 编辑器 -->
  <div class="editcont">
    <EditorContent style="padding: 8px;  overflow-y: auto;" :editor="editor" />
  </div>
  <!-- <el-button @click="addComment" type="warning">添加批注</el-button> -->
  <editor-content :editor="editor" class="editor" />

  <!-- ----------------- 段评 ---------------- -->

  <el-dialog v-model="dialogVisible" title="段评" width="30%" :before-close="handleClose">
    <div v-for="(comment, index) in comments" :key="index" class="comment-item">
      <span>{{ comment.author }}:</span>
      <el-text type="primary">{{ comment.content }}</el-text>
      <br>
      <el-text size="small">{{ comment.createDate }}</el-text>
    </div>
    <el-input v-model="commentText" placeholder="留下你的评论吧..." />
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">评 论</el-button>
        <el-button type="danger" @click="dialogVisible = false">退 出</el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import bubbleMenu from '@/components/index-center-s/bubble-menu/index.vue';
import { defineComponent, onMounted, onBeforeUnmount, ref, watch, nextTick } from 'vue';
import { Editor, EditorContent, useEditor } from '@tiptap/vue-3';
import Underline from '@tiptap/extension-underline'
// 列表
import { Markdown } from 'tiptap-markdown';
import ListItem from '@tiptap/extension-list-item'
import OrderedList from '@tiptap/extension-ordered-list'
import BulletList from '@tiptap/extension-bullet-list'
import Highlight from '@tiptap/extension-highlight'
// 代码
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight'
import css from 'highlight.js/lib/languages/css'
import js from 'highlight.js/lib/languages/javascript'
import ts from 'highlight.js/lib/languages/typescript'
import html from 'highlight.js/lib/languages/xml'
import { common, createLowlight } from 'lowlight'
// 字数统计
//   import CharacterCount from '@tiptap/extension-character-count'
import StarterKit from '@tiptap/starter-kit'
import Placeholder from '@tiptap/extension-placeholder'
//   import { UndoRound, MoreHorizOutlined } from '@vicons/material'
import TaskItem from '@tiptap/extension-task-item'
import TaskList from '@tiptap/extension-task-list'

// 使用Pinia
import { useEditorStore } from '@/stores/editStore'
//   import EditorMenu from './EditorMenu/index.vue'
import Document from '@tiptap/extension-document'


import { loadHeadings } from '../index-left/index-dagang/dagang';
import { ElMessage, ElMessageBox } from 'element-plus'
import { CommentPlugin, CommentPluginKey } from '@/tiptap/extensions/CommentPlugin'
import { useUserStore } from '@/stores/userStore';
import { currentNodeInfo } from '@/stores/currentNodeStore';
import { useCommentStore } from '@/stores/commentStore'
import { useBadgeStroe } from '@/stores/badgeStroe';
import { ParagraphBadge } from '@/tiptap/extensions/ParagraphBadge';
import { uuid } from '@/utils/uuid';
import { ExtendedImage } from '@/tiptap/extensions/ExtendedImage'
import { SaveContentExtension } from '@/tiptap/extensions/SaveContentExtension';
import { useCommentPluginStore } from '@/stores/commentPluginStore';
// 定义组件
const props =defineProps({
    width: {
      type: Number,
      required: true,
    },
  });

const useStroe = useBadgeStroe();
const dialogVisible = ref(false); // 使用ref定义响应式对话框显示状态
const currentParagraphPos = ref(''); // 当前点击段落的位置
const commentText = ref('');
const comments = ref([] as any[]); // 定义评论列表


const userStore = useUserStore();

const lowlight = createLowlight()
lowlight.register({ html, ts, css, js })
const editorStore = useEditorStore()
 const commentPlugin = useCommentPluginStore().getPlugin()
const editor = useEditor({
  //是否可编辑
  editable: false,
  content: ``,
  extensions: [
    ExtendedImage,
    Underline,
    Markdown,
    Document,
    // 添加自定义段落扩展-EL badge 徽章  段评
    ParagraphBadge.configure({
      HTMLAttributes: {
        class: 'paragraph-container',
      },
    }),

    StarterKit.configure({
      heading: {
        levels: [1, 2, 3, 4, 5],
      },
      blockquote: {
        HTMLAttributes: {
          class: 'tiptap-blockquote', // 自定义 class
        },
      },
      paragraph: {
        HTMLAttributes: {
          class: 'paragraph-class', // 确保这里配置了
        },

      },
    }),
    Highlight.configure({ multicolor: true }),
    TaskList,
    TaskItem,
    Placeholder.configure({
      placeholder: '请输入文本 …'
    }),
    SaveContentExtension,
    OrderedList,
    BulletList,
    ListItem,
    CodeBlockLowlight.configure({
      lowlight,
      defaultLanguage: 'javascript',
    }),

  ],
  onUpdate({ editor }) {
    //改完一次就加载一次标题
    loadHeadings()
    //标签存到pinia
    editorStore.setEditor(editor, editor.getHTML())

  },
  onCreate({ editor }) {
    loadHeadings()
    editorStore.setEditorInstance(editor)
    //ai  补全
    editor.registerPlugin(commentPlugin)

    //自定义徽章点击事件
    document.addEventListener('paragraph-comment-click', (event: CustomEvent) => {
      // console.log('接收到段落评论点击事件');
      const { id } = event.detail;  //
      // console.log('===============', id);

      // console.log("Event=-=-=-=-=", event);
      // currentParagraphPos.value = id;

      dialogVisible.value = true;
      console.log("接收到段落评论点击事件id:", id)
      // selectBadge();
    });
  },
  injectCSS: false,
})

//查徽章段评
const selectBadge = async () => {
  const data = {
    paragraphId: currentParagraphPos.value
  }
  await useStroe.getBadgeByParagraphId(data)
  comments.value = useStroe.badgeInfoList

}

//新增评论
const handleConfirm = async () => {
  if (commentText.value == null || commentText.value.trim() == "") {
    ElMessage.error('评论不能为空！')
    return
  }
  const data = {
    id: `user-${uuid()}`,
    paragraphId: currentParagraphPos.value,
    content: commentText.value,
    author: userStore.user.name,
    //生成随机本地时间
    createDate: new Date().toLocaleString()
  }
  await useStroe.addBadge(data)
  commentText.value = '' //清空输入栏
  ElMessage.success('评论成功')
  selectBadge()
}

// 保存按钮




onMounted(() => {
  //同步操作 后期初始库内容
  nextTick(async () => {
    if (editor.value) {
      //  前一步应先设置路由
      editor.value.commands.setContent(editorStore.getHtml(), false);
    }

  });
})
const addComment = async () => {
  const { state, view } = editor.value
  const { from, to } = state.selection

  if (from === to) {
    ElMessageBox.alert('请先选中一段文字后再添加批注', '提示')
    return
  }

  const noteId = currentNodeInfo().nodeId
  const userId = useUserStore().user.id
  const commentId = `${noteId}_${userId}_${from}_${to}`

  const decoSet = CommentPluginKey.getState(state)
  const hasOverlap = decoSet.find(from, to).some(d => {
    const data = d.spec?.commentData
    if (!data) return false
    return !(data.to <= from || data.from >= to)
  })

  if (hasOverlap) {
    ElMessageBox.alert('该范围与已有批注重叠，请选择不同范围', '提示')
    return
  }

  const result = await ElMessageBox.prompt('请输入批注内容', '添加批注', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '不能为空'
  })

  const anchorText = state.doc.textBetween(from, to)

  const commentData = {
    id: commentId,
    noteId,
    userId,
    from,
    to,
    comment: result.value,
    anchorText,
    broken: false
  }

  //在一个 setMeta 中同时传 add/remove（如果需要 remove，确保不会覆盖）
  const tr = state.tr.setMeta(CommentPluginKey, { add: commentData })
  view.dispatch(tr)
  const commentStore = useCommentStore()
  commentStore.addComment(commentData)
}




</script>
<style>
.center{
  background-image: url('@/assets/bg.png');
  z-index: 100;
}
.openai-button {
  position: fixed;
  background-color: #d4b5cb;
  top: 20px;
  right: 5%;
  z-index: 1000;
  border-radius: 50%;
}

.tiptap-comment {
  background-color: rgba(255, 230, 0, 0.4);
  border-bottom: 1px dashed orange;
  cursor: pointer;
}

/* 确保 ProseMirror 内容正确显示 */
.ProseMirror {
  outline: none;
  min-height: 100px;
}

/* .EditMain{
    position: relative;
    width:100vw;
    height: 100vh;

    display: grid;
    grid-template-columns: 20% 60% 20%;

  } */



.editcont {
  position: relative;
  /* width: 100vw;
    height: 100vh; */
  overflow: hidden;



}
</style>

<style lang="scss">
b {
  font-weight: bold;
}



.ProseMirror {
  overflow-y: auto; // 改为 auto 只在需要时显示滚动条
  /// 编辑器滚动效果  以下是AI生成的
  height: 90vh; // 必须设置固定高度或最大高度
  min-height: 500px; // 可选，确保最小高度
  padding: 10px; // 添加内边距
  background: #fff; // 背景色

  // 自定义滚动条样式
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;

  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #c1c1c1;
    border-radius: 4px;
  }
}

.ProseMirror p {
  margin: 0;
  color: #333
}

.ProseMirror:focus {
  outline: none;
}

.tiptap p.is-editor-empty:first-child::before {
  color: #adb5bd;
  content: attr(data-placeholder);
  float: left;
  height: 0;
  pointer-events: none;
}

.tiptap {
  >*+* {
    margin-top: 0.75em;
  }

  ul {
    padding: 0 2rem;
    list-style: square;
  }

  ol {
    padding: 0 2rem;
    list-style: decimal;
  }

  table {
    border-collapse: collapse;
    table-layout: fixed;
    width: 100%;
    margin: 0;
    overflow: hidden;

    td,
    th {
      min-width: 1em;
      border: 2px solid #ced4da;
      padding: 3px 5px;
      vertical-align: top;
      box-sizing: border-box;
      position: relative;

      >* {
        margin-bottom: 0;
      }
    }

    th {
      font-weight: bold;
      text-align: left;
      background-color: #f1f3f5;
    }

    .selectedCell:after {
      z-index: 2;
      position: absolute;
      content: '';
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      background: rgba(200, 200, 255, 0.4);
      pointer-events: none;
    }

    .column-resize-handle {
      position: absolute;
      right: -2px;
      top: 0;
      bottom: -2px;
      width: 4px;
      background-color: #adf;
      pointer-events: none;
    }

    p {
      margin: 0;
    }
  }

  pre {
    background: #0d0d0d;
    color: #fff;
    font-family: 'JetBrainsMono', monospace;
    padding: 0.75rem 1rem;
    border-radius: 0.5rem;

    code {
      color: inherit;
      padding: 0;
      background: none;
      font-size: 0.8rem;
    }

    .hljs-comment,
    .hljs-quote {
      color: #616161;
    }

    .hljs-variable,
    .hljs-template-variable,
    .hljs-attribute,
    .hljs-tag,
    .hljs-name,
    .hljs-regexp,
    .hljs-link,
    .hljs-name,
    .hljs-selector-id,
    .hljs-selector-class {
      color: #f98181;
    }

    .hljs-number,
    .hljs-meta,
    .hljs-built_in,
    .hljs-builtin-name,
    .hljs-literal,
    .hljs-type,
    .hljs-params {
      color: #fbbc88;
    }

    .hljs-string,
    .hljs-symbol,
    .hljs-bullet {
      color: #b9f18d;
    }

    .hljs-title,
    .hljs-section {
      color: #faf594;
    }

    .hljs-keyword,
    .hljs-selector-tag {
      color: #70cff8;
    }

    .hljs-emphasis {
      font-style: italic;
    }

    .hljs-strong {
      font-weight: 700;
    }
  }
}

.tableWrapper {
  overflow-x: auto;
}

.resize-cursor {
  cursor: ew-resize;
  cursor: col-resize;
}

.paragraph-class {
  margin: 0 0 1rem 0; // 默认 margin
  line-height: 1.6;

  // 嵌套选择器（SCSS 特性）
  &:first-child {
    margin-top: 0;
  }

  &:last-child {
    margin-bottom: 0;
  }

  // 特定情况下的段落样式
  &.has-dropcap::first-letter {
    float: left;
    font-size: 3em;
    line-height: 1;
    margin-right: 0.5rem;
    font-weight: bold;
  }

  // 暗黑模式适配
  .dark & {
    color: #e2e8f0;
  }
}

.tiptap-blockquote {
  border-left: 4px solid #fd0d99;
  background: #f8f9fa;
  padding: 0.5rem 1rem;
  margin: 1rem 0;
}


/* 段落容器 - 为徽章提供定位上下文 */
.paragraph-container {
  position: relative;
  margin-bottom: 1rem;
  padding-left: 3px;
  /* 调试用边框 - 取消注释可查看容器范围 */
  // border: 1px solid rgb(224, 208, 208);
  // background-color: rgba(214, 29, 29, 0.1);
}

/* 徽章包装器 - 控制徽章位置和间距 */
.badge-wrapper {
  position: relative;
  display: inline-block;
  vertical-align: top;
  margin-left: 2px;
  padding: 0;
  width: 16px;
  height: 16px;
  cursor: pointer;

  /* 徽章弹出动画 */
  transition: transform 0.2s ease-out;

  &:hover {
    transform: translateY(-1px);
  }
}

/* Element UI 徽章基础样式 */
.el-badge {
  position: relative;
  z-index: 10;
}

/* 徽章内容 - 核心圆形指示器 */
.el-badge__content {
  /* 尺寸与形状 */
  width: 13px !important;
  height: 13px !important;
  border-radius: 50% !important;

  /* 内容居中 */
  display: flex;
  align-items: center;
  justify-content: center;

  /* 视觉样式 */
  font-size: 10px;
  background-color: #eb2020;
  color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);

  /* 消除默认样式干扰 */
  padding: 0 !important;
  margin: 0 !important;

  /* 状态过渡 */
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);

  /* 不同状态样式 */
  &.unread {
    background-color: #722ed1;
    box-shadow: 0 1px 3px rgba(114, 46, 209, 0.2);
  }

  &.highlight {
    background-color: #ff6b9d;
    box-shadow: 0 1px 3px rgba(255, 107, 157, 0.2);
  }
}

/* 徽章交互效果 */
.el-badge__content:hover {
  transform: scale(1.2);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  z-index: 20;
}

/* 徽章动画效果 */
@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }

  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }

  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.el-badge__content.pulse {
  animation: pulse 1.5s infinite;
}


/* ================ 段评弹框整体样式 ================ */
.el-dialog {
  width: 550px !important;
  /* 减小宽度，减少左右留白 */
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  overflow: hidden;

  &__header {
    background: #a5b7f1;
    padding: 12px 16px;
    /* 减少顶部内边距 */
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: none;

    &-title {
      color: #fff;
      font-size: 14px;
      font-weight: 500;
    }
  }

  &__body {
    padding: 12px 14px;
    /* 减少左右留白 */
    max-height: 350px;
    overflow-y: auto;
  }

  &__footer {
    padding: 10px 14px;
    border-top: 1px solid #f0f0f0;
  }
}

/* ================ 评论列表样式 ================ */
.comment-list {
  margin-bottom: 12px;
}

.comment-item {
  margin-bottom: 14px;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }

  /* 用户名 - 左对齐，单独一行 */
  >span {
    display: block;
    color: #333;
    font-weight: 500;
    font-size: 13px;
    margin-bottom: 4px;
  }

}

/* ================ 评论输入区域 ================ */
.comment-input-area {
  .el-input {
    width: 100%;
    margin-bottom: 10px;

    &__inner {
      border-radius: 4px;
      padding: 8px 10px;
      font-size: 13px;
      border: 1px solid #dcdfe6;
    }
  }
}

/* ================ 底部按钮栏 ================ */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 8px 0;

  .el-button {
    padding: 4px 12px;
    font-size: 12px;
    margin-left: 8px;
  }
}

/* ================ 徽章样式 ================ */
.paragraph-badge-container {
  position: relative;
  display: inline-block;
  margin-left: 2px;
}

// 默认隐藏徽章
.el-badge.custom-badge {
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease, visibility 0.3s ease;
}

// 当鼠标悬停在段落容器时显示徽章
.paragraph-container:hover .el-badge.custom-badge {
  opacity: 1;
  visibility: visible;
}

.el-badge__content {
  width: 13px !important;
  height: 13px !important;
  border-radius: 50% !important;
  font-size: 9px;
  background-color: #ff6b9d;
  color: #fff;
  padding: 0 !important;
  margin: 0 !important;
}
</style>
